import type { FormInstance } from 'element-plus'
import type { MenuTypeEnum, SystemMenuStateType } from '~/store/system/typings'
import type { SystemMenuOptionsType, SystemMenuDataItemType } from './typings'
import { defineComponent, ref, reactive, onMounted } from 'vue'
import { useStore } from 'vuex'
import {
  ElDialog,
  ElForm,
  ElRow,
  ElCol,
  ElFormItem,
  ElInput,
  ElInputNumber,
  ElTreeSelect,
  ElRadioGroup,
  ElRadio,
  ElButton,
  ElMessage,
  ElIcon,
  ElSpace,
  ElImage
} from 'element-plus'
import { Plus, EditPen, Menu } from '@element-plus/icons-vue'
import InputTextarea from '~/components/ProForm/InputTextarea'
import BaseUpload from '~/components/ProForm/BaseUpload'
import MenuIconModal from '../components/SystemMenu/MenuIconModal'
import AliIcon from '~/components/AliIocn'
import useVuexGetters from '~/hooks/useVuexGetters'
import { GUTTER, SPAN_STYLE_DOUBLE } from '~/utils/const'
import { handleTrim } from '~/utils/util'
import styles from '../index.module.scss'

export default defineComponent({
  name: 'SystemMenuOptions',
  props: ['visible', 'type', 'record'],
  emits: ['cancel'],
  setup(props: SystemMenuOptionsType, { emit }) {
    const store = useStore()
    const visibleRef = ref<boolean>()
    const ruleFormRef = ref<FormInstance>()
    const formValues = reactive<SystemMenuDataItemType>({})
    const systemMenuState = useVuexGetters('systemMenu', [
      'menuTreeSelectList',
      'menuTypeSelectList',
      'menuTypeEnum',
      'buttonFeaturesSelectList',
      'buttonFeaturesEnum',
      'newWindowSelectList',
      'newWindowEnum',
      'menuSystemTypeSelectList',
      'menuSystemTypeEnum'
    ])
    const title = { add: '新增', update: '编辑', read: '查看' }
    // 关闭弹框事件回调
    const handleCloseModal = () => {
      emit('cancel')
    }

    // 获取菜单详情
    const handleGetMenuInfo = async () => {
      const res = await store.dispatch('systemMenu/GetSystemMenuInfo', { id: props.record.id })
      Object.assign(formValues, {
        ...(res?.data || {}),
        imageUrl: res?.data?.imageUrl ? res?.data?.imageUrl?.split?.(',') : []
      })
    }

    // 提交表单
    const handleSubmitForm = () => {
      if (!ruleFormRef.value) return
      ruleFormRef.value.validate(async (valid) => {
        if (!valid) return
        const params = { ...formValues }
        params.name = params.name && handleTrim(params.name)
        params.path = params.path && handleTrim(params.path)
        params.code = params.code && handleTrim(params.code)
        params.remark = params.remark && handleTrim(params.remark)
        params.imageUrl = params.imageUrl?.length ? (params.imageUrl as string[]).join(',') : ''
        const res = await store.dispatch('systemMenu/OptionSystemMenuInfo', params)
        if (res?.code === 200) {
          ElMessage({ type: 'success', message: '操作成功' })
          handleCloseModal()
        }
      })
    }

    // 上传成功回调
    const handleUploadSuccess = (result: Record<string, any>) => {
      const link = result?.data?.link
      if (link) {
        (formValues.imageUrl as string[])?.push(link)
      }
    }
    // 移除对应的文件
    const handleRemoveUploadFile = (file: Record<string, any>) => {
      const link = file?.response?.data?.link
      if (link) {
        formValues.imageUrl = (formValues.imageUrl as string[])?.filter((item) => item !== link)
      }
    }

    onMounted(() => {
      if (props.record?.id) {
        props.type !== 'add'
          ? handleGetMenuInfo()
          : Object.assign(formValues, { parentId: props.record?.id })
      }
    })

    return () => {
      const { type, visible } = props
      return (
        <ElDialog
          title={(title[type] as string) || '查看'}
          modelValue={visible}
          closeOnClickModal={false} // 点遮罩层不关弹窗
          draggable // 可拖拽
          beforeClose={handleCloseModal}
          v-slots={
            type !== 'read' && {
              footer: () => (
                <>
                  <ElButton type="primary" onClick={handleSubmitForm}>
                    <ElIcon>
                      <EditPen />
                    </ElIcon>
                    &nbsp; {type === 'add' ? '保存' : '修改'}
                  </ElButton>
                  <ElButton onClick={handleCloseModal}>取消</ElButton>
                </>
              )
            }
          }
        >
          <ElForm label-width="100px" ref={ruleFormRef} model={formValues}>
            <ElRow gutter={GUTTER}>
              <ElCol {...SPAN_STYLE_DOUBLE}>
                <ElFormItem
                  prop="name"
                  label="菜单名称"
                  rules={[{ required: true, message: '请输入菜单名称' }]}
                >
                  {type === 'read' ? (
                    formValues.name
                  ) : (
                    <ElInput v-model={formValues.name} placeholder="请输入菜单名称" />
                  )}
                </ElFormItem>
              </ElCol>
              <ElCol {...SPAN_STYLE_DOUBLE}>
                <ElFormItem
                  prop="path"
                  label="路由地址"
                  rules={[{ required: true, message: '请输入路由地址' }]}
                >
                  {type === 'read' ? (
                    formValues.path
                  ) : (
                    <ElInput v-model={formValues.path} placeholder="请输入路由地址" />
                  )}
                </ElFormItem>
              </ElCol>
              <ElCol {...SPAN_STYLE_DOUBLE}>
                <ElFormItem
                  prop="parentId"
                  label="上级菜单"
                  rules={[{ required: false, message: '请选择上级菜单' }]}
                >
                  {type === 'read' ? (
                    formValues.parentName
                  ) : (
                    <ElTreeSelect
                      v-model={formValues.parentId}
                      placeholder="请选择上级菜单"
                      data={systemMenuState.menuTreeSelectList.value}
                      checkStrictly
                      props={{
                        label: 'title',
                        value: 'key'
                      }}
                    />
                  )}
                </ElFormItem>
              </ElCol>
              <ElCol {...SPAN_STYLE_DOUBLE}>
                <ElFormItem
                  prop="source"
                  label="菜单图标"
                  // rules={[{ required: true, message: '请输入菜单图标' }]}
                >
                  {type === 'read' ? (
                    <>
                      <AliIcon type={formValues.source!} />
                      &emsp;
                      {formValues.source}
                    </>
                  ) : (
                    <ElInput
                      v-model={formValues.source}
                      // readonly
                      clearable
                      placeholder="请输入菜单图标"
                      v-slots={{
                        prepend: () => (
                          <ElButton text icon={<AliIcon type={formValues.source!} />} />
                        ),
                        append: () => (
                          <ElButton
                            text
                            icon={Menu}
                            onClick={() => {
                              visibleRef.value = true
                            }}
                          />
                        )
                      }}
                    />
                  )}
                </ElFormItem>
              </ElCol>
              <ElCol {...SPAN_STYLE_DOUBLE}>
                <ElFormItem
                  prop="code"
                  label="菜单编号"
                  rules={[{ required: true, message: '请输入菜单编号' }]}
                >
                  {type === 'read' ? (
                    formValues.code
                  ) : (
                    <ElInput v-model={formValues.code} placeholder="请输入菜单编号" />
                  )}
                </ElFormItem>
              </ElCol>
              <ElCol {...SPAN_STYLE_DOUBLE}>
                <ElFormItem
                  prop="category"
                  label="菜单类型"
                  rules={[{ required: true, message: '请输入菜单类型' }]}
                >
                  {type === 'read' ? (
                    systemMenuState?.menuTypeEnum.value?.[formValues.category!] ||
                    formValues.category
                  ) : (
                    <ElRadioGroup v-model={formValues.category}>
                      {systemMenuState?.menuTypeSelectList.value?.map((item: MenuTypeEnum) => (
                        <ElRadio label={item?.dictKey}>{item?.dictValue}</ElRadio>
                      ))}
                    </ElRadioGroup>
                  )}
                </ElFormItem>
              </ElCol>
              <ElCol {...SPAN_STYLE_DOUBLE}>
                <ElFormItem
                  prop="action"
                  label="按钮功能"
                  rules={[{ required: true, message: '请输入按钮功能' }]}
                >
                  {type === 'read' ? (
                    systemMenuState?.buttonFeaturesEnum.value?.[formValues.action!] ||
                    formValues.action
                  ) : (
                    <ElRadioGroup v-model={formValues.action}>
                      {systemMenuState?.buttonFeaturesSelectList.value?.map(
                        (item: SystemMenuStateType['buttonFeaturesEnum']) => (
                          <ElRadio label={item?.key}>{item?.value}</ElRadio>
                        )
                      )}
                    </ElRadioGroup>
                  )}
                </ElFormItem>
              </ElCol>
              <ElCol {...SPAN_STYLE_DOUBLE}>
                <ElFormItem
                  prop="sort"
                  label="菜单排序"
                  rules={[{ required: true, message: '请输入菜单排序' }]}
                >
                  {type === 'read' ? (
                    formValues.sort
                  ) : (
                    <ElInputNumber
                      v-model={formValues.sort}
                      min={0}
                      controls-position="right"
                      placeholder="请输入菜单排序"
                    />
                  )}
                </ElFormItem>
              </ElCol>
              <ElCol {...SPAN_STYLE_DOUBLE}>
                <ElFormItem
                  prop="isOpen"
                  label="新窗口"
                  rules={[{ required: false, message: '请输入新窗口' }]}
                >
                  {type === 'read' ? (
                    systemMenuState?.newWindowEnum.value?.[formValues.isOpen!] || formValues.isOpen
                  ) : (
                    <ElRadioGroup v-model={formValues.isOpen}>
                      {systemMenuState?.newWindowSelectList.value?.map(
                        (item: SystemMenuStateType['newWindowEnum']) => (
                          <ElRadio label={item?.key}>{item?.value}</ElRadio>
                        )
                      )}
                    </ElRadioGroup>
                  )}
                </ElFormItem>
              </ElCol>
              <ElCol {...SPAN_STYLE_DOUBLE}>
                <ElFormItem
                  prop="type"
                  label="类型"
                  rules={[{ required: false, message: '请输入类型' }]}
                >
                  {type === 'read' ? (
                    systemMenuState?.menuSystemTypeEnum.value?.[formValues.type!] || formValues.type
                  ) : (
                    <ElRadioGroup v-model={formValues.type}>
                      {systemMenuState?.menuSystemTypeSelectList.value?.map(
                        (item: SystemMenuStateType['menuSystemTypeEnum']) => (
                          <ElRadio label={item?.key}>{item?.value}</ElRadio>
                        )
                      )}
                    </ElRadioGroup>
                  )}
                </ElFormItem>
              </ElCol>
              <ElCol>
                <ElFormItem
                  prop="remark"
                  label="菜单备注"
                  rules={[{ required: false, message: '请输入菜单备注' }]}
                >
                  {type === 'read' ? (
                    formValues.remark
                  ) : (
                    <InputTextarea
                      v-model:inputTextareaValue={formValues.remark}
                      placeholderName="请输入菜单备注"
                      limitLength={1000}
                    />
                  )}
                </ElFormItem>
              </ElCol>
              <ElCol>
                <ElFormItem
                  label="图片"
                  prop="imageUrl"
                  rules={[{ required: false, message: '请上传图片', trigger: 'change' }]}
                >
                  {type === 'read' ? (
                    <ElSpace wrap>
                      {(formValues.imageUrl as string[])?.map?.((imgUrl, index, arr) => (
                        <ElImage
                          class={styles['image-thumbnail']}
                          src={imgUrl}
                          previewSrcList={arr}
                          initialIndex={index}
                          fit="cover"
                        />
                      ))}
                    </ElSpace>
                  ) : (
                    <BaseUpload
                      listType="picture-card"
                      fileList={(formValues.imageUrl as string[])?.map?.((item) => ({
                        name: '图片',
                        url: item
                      }))}
                      accept="image/*"
                      onSuccess={handleUploadSuccess}
                      onRemove={handleRemoveUploadFile}
                    >
                      <ElIcon>
                        <Plus />
                      </ElIcon>
                      点击上传
                    </BaseUpload>
                  )}
                </ElFormItem>
              </ElCol>
            </ElRow>
          </ElForm>
          {visibleRef.value && (
            <MenuIconModal
              visible={visibleRef.value}
              cancel={() => {
                visibleRef.value = false
              }}
              onChangIcon={(icon) => {
                formValues.source = icon
              }}
            />
          )}
        </ElDialog>
      )
    }
  }
})
